package com.dongdongshop.util;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class HttpClientPostDemo {
    public static String httpPostParam(Map<String,Object> map,String url) throws Exception {
        //1.创建一个HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //2.创建一个Post请求
        HttpPost httpost= new HttpPost(url);
        //2.1 声明List集合,封装表单中的参数
        List<NameValuePair> params = new ArrayList<>();

        Iterator<Map.Entry<String,Object>> it= map.entrySet().iterator();
        while(it.hasNext()){
            Map.Entry<String,Object> entry=it.next();
            params.add(new BasicNameValuePair( entry.getKey(), (String) entry.getValue()));
        }

        params.add(new BasicNameValuePair("firstChar","A"));
        //2.2创建表单的Entity对象,第一个参数是封装好的表单数据,第二个参数是编码
        UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(params,"utf8");
        //2.3设置表单的Entity对象到Post请求中
        httpost.setEntity(urlEncodedFormEntity);

        CloseableHttpResponse response = null;
        String content = null;
        try {
            //3.使用HttpClient来执行Post请求,获取response
            response = httpClient.execute(httpost);
            //4.处理response,解析相应  200:响应成功
            if(response.getStatusLine().getStatusCode() == 200){
                /*
                 * 第一个参数是响应体
                 * 第二个参数是编码格式
                 * */
                 content = EntityUtils.toString(response.getEntity(), "utf8");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                //5.释放资源
                if(response != null){
                    response.close();
                }if(httpClient != null){
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return content;
    }
}
